package com.advert.presentation.converter;

import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.ConverterException;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.text.ParsePosition;


public class CurrencyConverter extends ConverterBase {

    protected Object convertToObject(FacesContext facesContext, UIComponent uiComponent, String s) {
        BigDecimal retVal = null;
        try {
            DecimalFormat decimalFormat = new DecimalFormat("#,##0.00");
            decimalFormat.setDecimalFormatSymbols(new DecimalFormatSymbols(facesContext.getViewRoot().getLocale()));
            decimalFormat.setParseBigDecimal(true);
            decimalFormat.parse(s, new ParsePosition(0));
            retVal = new BigDecimal(decimalFormat.parse(s).doubleValue());
        } catch (Exception e) {
            throw new ConverterException(buildConversionErrorMessage("CURRENCY_FORMAT_INCORRECT"));
        }
        if (BigDecimal.ZERO.compareTo(retVal) > 0) {
            throw new ConverterException(buildConversionErrorMessage("SHOULD_BE_POSITIVE"));
        }
        return retVal;
    }

    protected String convertToString(FacesContext facesContext, UIComponent uiComponent, Object o) {
        DecimalFormat decimalFormat = new DecimalFormat("#,##0.##");
        decimalFormat.setDecimalFormatSymbols(new DecimalFormatSymbols(facesContext.getViewRoot().getLocale()));
        return decimalFormat.format(o);
    }

}
